//
//  OcrScanViewController.m
//  ICrEAM
//
//  Created by mac on 17/5/8.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "OcrScanViewController.h"
#if TARGET_IPHONE_SIMULATOR//模拟器
#elif TARGET_OS_IPHONE//真机
#import "SmartOCR.h"
#endif

//屏幕的宽、高
//#define ScreenWidth  [UIScreen mainScreen].bounds.size.width
//#define ScreenHeight [UIScreen mainScreen].bounds.size.height

@interface OcrScanViewController ()<AVCaptureVideoDataOutputSampleBufferDelegate>{
    BOOL _on;//闪光灯是否打开
#if TARGET_IPHONE_SIMULATOR//模拟器
#elif TARGET_OS_IPHONE//真机
    SmartOCR *_ocr;//核心
#endif

    BOOL _isRecoging;//是否正在识别
    int _currentRecogType;//当前识别的子类型
    NSString *_currentOCRID;//当前识别的子类型代码
    AVCaptureConnection *_videoConnection;
    
}
@property (weak, nonatomic) IBOutlet UIView *scanView;
@property (nonatomic, strong) UIImageView *line;//交互线
@property (nonatomic, strong) NSTimer *lineTimer;//交互线控制
@end

@implementation OcrScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
#if TARGET_IPHONE_SIMULATOR//模拟器
#elif TARGET_OS_IPHONE//真机

    //[self.view setBackgroundColor:[UIColor clearColor]];
    
    //注册通知，监听OCRScanView的Frame改变，重新设置检边参数Roi
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resetRoi:) name:@"ScanViewFrameChangedAndResetRoi" object:nil];
    //注册通知，监听设备方向，重设视频流和预览图层方向
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
    
    //初始化识别核心
    [self initOCRSource];
    
    //初始化相机
    [self initialize];
    
    //创建相机界面控件
//    self.resultDataSource = [NSMutableArray array];
//    self.fieldDataSource = [NSMutableArray array];
//    for (SubType *subtype in self.subTypes) {
//        
//        [self.resultDataSource addObject:@""];
//        [self.fieldDataSource addObject:@"VIN码"];
//        [self.imagePaths addObject:@""];
//    }
    [self setOverlayPickerView];
    
//    CGRect flashBtnFrame = CGRectMake(CGRectGetMaxX(self.sframe)-54, 28, 30, 30);
//    UIButton *flashBtn = [[UIButton alloc]initWithFrame:flashBtnFrame];
//    [flashBtn setImage:[UIImage imageNamed:@"flash_camera_btn"] forState:UIControlStateNormal];
//    [flashBtn addTarget:self action:@selector(flashBtn) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:flashBtn];
    [self createBackBtn];
    
#endif
}
#if TARGET_IPHONE_SIMULATOR//模拟器
#elif TARGET_OS_IPHONE//真机

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //隐藏navigationBar
    self.navigationController.navigationBarHidden = YES;
    [self.session startRunning];
}
- (void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.session stopRunning];
}

- (void) dealloc{
    //注销通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:
     @"ScanViewFrameChangedAndResetRoi" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
    
}

#pragma mark --------------------初始化---------------------------
- (void) initOCRSource
{
    //初始化核心
    _ocr = [[SmartOCR alloc] init];
    //
    int init = [_ocr initOcrEngineWithDevcode:@"5LIK5RW355SO5YA"];
    NSLog(@"初始化返回值 = %d 核心版本号 = %@", init, [_ocr getVersionNumber]);
    
    //添加模板
    NSString *templateFilePath = [[NSBundle mainBundle] pathForResource:@"SZHY" ofType:@"xml"];
    int addTemplate = [_ocr addTemplateFile:templateFilePath];
    NSLog(@"添加主模板返回值 = %d", addTemplate);
    
    //设置识别类型
    _currentOCRID=@"SV_ID_VIN_CARWINDOW";
    int currentTemplate = [_ocr setCurrentTemplate:_currentOCRID];
    
    //设置识别区域检边参数
    [self setROIWithRect:_scanView.frame];
    NSLog(@"设置模板返回值：%d", currentTemplate);
}

- (void) setROIWithRect:(CGRect)rect
{
    //设置识别区域
    CGFloat tempWidth;
    CGFloat tempHeight;
    if (ScreenHeight>ScreenWidth) {
        tempHeight = ScreenHeight;
        tempWidth = ScreenWidth;
    }else{
        tempHeight = ScreenWidth;
        tempWidth = ScreenHeight;
    }
    CGFloat scale = 1080.0/tempWidth; //1080为当前分辨率(1920*1080)中的宽
    int dValue = (tempWidth/1080*1920-tempHeight)*scale*0.5;
    int sTop = (CGRectGetMinY(rect))*scale;
    int sBottom = CGRectGetMaxY(rect)*scale;
    int sLeft = CGRectGetMinX(rect)*scale;
    int sRight = (CGRectGetMaxX(rect))*scale;
    
    if (ScreenHeight>ScreenWidth) {
        [_ocr setROIWithLeft:sLeft Top:sTop+dValue Right:sRight Bottom:sBottom+dValue];
    }else{
        [_ocr setROIWithLeft:sLeft+dValue Top:sTop Right:sRight+dValue Bottom:sBottom];
    }
}

//初始化相机
- (void) initialize
{
    //判断摄像头授权
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
        
        UIAlertView * alt = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"allowCamare", nil) message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alt show];
        return;
    }
    //1.创建会话层
    self.session = [[AVCaptureSession alloc] init];
    //设置图片品质，此分辨率为最佳识别分辨率，建议不要改动
    [self.session setSessionPreset:AVCaptureSessionPreset1920x1080];
    
    //2.创建、配置输入设备
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    
    for (AVCaptureDevice *device in devices)
    {
        if (device.position == AVCaptureDevicePositionBack)
        {
            self.captureInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
        }
    }
    [self.session addInput:self.captureInput];
    
    ///创建、配置预览输出设备
    AVCaptureVideoDataOutput *captureOutput = [[AVCaptureVideoDataOutput alloc] init];
    captureOutput.alwaysDiscardsLateVideoFrames = YES;
    dispatch_queue_t queue;
    queue = dispatch_queue_create("cameraQueue", NULL);
    [captureOutput setSampleBufferDelegate:self queue:queue];
    NSString* key = (NSString*)kCVPixelBufferPixelFormatTypeKey;
    NSNumber* value = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA];
    NSDictionary* videoSettings = [NSDictionary dictionaryWithObject:value forKey:key];
    [captureOutput setVideoSettings:videoSettings];
    [self.session addOutput:captureOutput];
    
    //3.创建、配置输出
    self.captureOutput = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey,nil];
    [self.captureOutput setOutputSettings:outputSettings];
    [self.session addOutput:self.captureOutput];
    
    //4.设置预览
    self.preview = [AVCaptureVideoPreviewLayer layerWithSession: self.session];
    self.preview.frame =CGRectMake(0, 68, self.sframe.size.width, self.sframe.size.height-68);
    self.preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.view.layer insertSublayer:self.preview atIndex:0];
    
    //5.设置视频流和预览图层方向
    for (AVCaptureConnection *connection in captureOutput.connections) {
        for (AVCaptureInputPort *port in [connection inputPorts]) {
            if ([[port mediaType] isEqual:AVMediaTypeVideo] ) {
                _videoConnection = connection;
                break;
            }
        }
        if (_videoConnection) { break; }
    }
    //根据设备方向设置视频流方向和预览图层方向
    UIDeviceOrientation currentDeviceOrientatin = [self orientationFormInterfaceOrientation];
    AVCaptureVideoOrientation currentVideoOrientation = [self avOrientationForDeviceOrientation:currentDeviceOrientatin];
    _videoConnection.videoOrientation = currentVideoOrientation;
    self.preview.connection.videoOrientation = currentVideoOrientation;
    
    //6启动相机
    [self.session startRunning];
}

- (void)createBackBtn
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake(24, 28, 30, 30)];
    [btn setImage:[UIImage imageNamed:@"back_item"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(cancleSYQRCodeReading) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}
//取消扫描
- (void)cancleSYQRCodeReading
{
    [self stopSYQRCodeReading];
    
    if (self.SYQRCodeCancleBlock)
    {
        self.SYQRCodeCancleBlock(self);
    }
}

- (void)stopSYQRCodeReading
{
    
    if (_lineTimer)
    {
        [_lineTimer invalidate];
        _lineTimer = nil;
    }

    //
    [self.session stopRunning];
    //
}

- (void)setOverlayPickerView
{
    NSLog(@"sacanView = %@",NSStringFromCGRect(self.scanView.frame));
    //画中间的基准线
    _line = [[UIImageView alloc] initWithFrame:CGRectMake(self.scanView.frame.origin.x, self.scanView.frame.origin.y, self.scanView.frame.size.width, 3)];
    [_line setImage:[UIImage imageNamed:@"img_line"]];
    [self.view addSubview:_line];
        _lineTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 / 20 target:self selector:@selector(animationLine) userInfo:nil repeats:YES];
    
}

//闪光灯按钮点击事件
- (void)flashBtn{
    
    AVCaptureDevice *device = [self cameraWithPosition:AVCaptureDevicePositionBack];
    if (![device hasTorch]) {
        //        NSLog(@"no torch");
    }else{
        [device lockForConfiguration:nil];
        if (!_on) {
            [device setTorchMode: AVCaptureTorchModeOn];
            _on = YES;
        }
        else
        {
            [device setTorchMode: AVCaptureTorchModeOff];
            _on = NO;
        }
        [device unlockForConfiguration];
    }
}

#pragma mark 上下滚动交互线
- (void)animationLine
{
    __block CGRect frame = _line.frame;
    
    static BOOL flag = YES;
    
    if (flag)
    {
        frame.origin.y = self.scanView.frame.origin.y;
        flag = NO;
        
        [UIView animateWithDuration:1.0 / 20 animations:^{
            
            frame.origin.y += 5;
            _line.frame = frame;
            
        } completion:nil];
    }
    else
    {
        if (_line.frame.origin.y >= self.scanView.frame.origin.y)
        {
            if (_line.frame.origin.y >= (self.scanView.frame.origin.y+self.scanView.frame.size.height-5))
            {
                frame.origin.y = self.scanView.frame.origin.y;
                _line.frame = frame;
                
                flag = YES;
            }
            else
            {
                [UIView animateWithDuration:1.0 / 20 animations:^{
                    
                    frame.origin.y += 5;
                    _line.frame = frame;
                    
                } completion:nil];
            }
        }
        else
        {
            flag = !flag;
        }
    }
    
}
//从摄像头缓冲区获取图像
#pragma mark - AVCaptureSession delegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
       fromConnection:(AVCaptureConnection *)connection
{
    //获取当前帧数据
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    CVPixelBufferLockBaseAddress(imageBuffer,0);
    uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer);
    int width = (int)CVPixelBufferGetWidth(imageBuffer);
    int height = (int)CVPixelBufferGetHeight(imageBuffer);
    
    //识别VIN码
    [self recogVINWithData:baseAddress width:width height:height];
    
    CVPixelBufferUnlockBaseAddress(imageBuffer,0);
}

//识别VIN码
- (void)recogVINWithData:(uint8_t *)baseAddress width:(int)width height:(int)height{
    //识别核心加载图像
    [_ocr loadStreamBGRA:baseAddress Width:width Height:height];
    //识别核心识别图像
    int recog = [_ocr recognize];
    if (recog == 0) {
        //识别成功，识别核心取结果
        NSString *result = [_ocr getResults];
        NSLog(@"VIN== %@",result);
        NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *imagePath = [documents[0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg", _currentOCRID]];
        //识别核心保存图片
        [_ocr saveImage:imagePath];
        if (result.length != 0) {
            //停止相机
            [_session stopRunning];
            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
            
//            //获取VIN车辆信息
//            [_ocr initVINEngine];
//            NSArray *vinInfo = [_ocr searchVINInfoWithVINCode:result];
//            NSString *allResult = @"";
//            for (NSDictionary *dict in vinInfo) {
//                allResult = [allResult stringByAppendingString:[NSString stringWithFormat:@"%@:%@\n", [dict allKeys][0], [dict objectForKey:[dict allKeys][0]]]];
//            }
//            NSLog(@"%@", allResult);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //VIN码
                if (self.SYQRCodeSuncessBlock) {
                    self.SYQRCodeSuncessBlock(self,result);
                }
            });
        }
    }
}
//获取摄像头位置
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position
{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices)
    {
        if (device.position == position)
        {
            return device;
        }
    }
    return nil;
}

#pragma mark -------------------—-NSNotification事件---------------------------
//OCRScanView的Frame改变，重新设置检边参数Roi
- (void)resetRoi:(NSNotification *)notification{
    NSString *rectString = [notification.userInfo objectForKey:@"scanViewFrame"];
    CGRect rect = CGRectFromString(rectString);
    [self setROIWithRect:rect];
}
//设备方向改变 重设视频流和预览图层方向
- (void)orientChange:(NSNotification *)notification{
    UIDeviceOrientation currentDeviceOrientatin = [self orientationFormInterfaceOrientation];
    AVCaptureVideoOrientation currentVideoOrientation = [self avOrientationForDeviceOrientation:currentDeviceOrientatin];
    _videoConnection.videoOrientation = currentVideoOrientation;
    self.preview.connection.videoOrientation = currentVideoOrientation;
    self.preview.frame =CGRectMake(0, 68, self.view.frame.size.width, self.view.frame.size.height-68);
    
}
#pragma mark --------------------监控设备旋转----------------------------
//判断当前应用方向
- (UIDeviceOrientation)orientationFormInterfaceOrientation{
    UIDeviceOrientation tempDeviceOrientation = UIDeviceOrientationLandscapeRight;
    UIInterfaceOrientation tempInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
    switch (tempInterfaceOrientation) {
        case UIInterfaceOrientationPortrait:
            tempDeviceOrientation = UIDeviceOrientationPortrait;
            break;
        case UIInterfaceOrientationPortraitUpsideDown:
            tempDeviceOrientation = UIDeviceOrientationPortraitUpsideDown;
            break;
        case UIInterfaceOrientationLandscapeLeft:
            tempDeviceOrientation = UIDeviceOrientationLandscapeRight;
            break;
        case UIInterfaceOrientationLandscapeRight:
            tempDeviceOrientation = UIDeviceOrientationLandscapeLeft;
            break;
            
        default:
            break;
    }
    return tempDeviceOrientation;
    
}
//设备方向变化对应视频流方向
- (AVCaptureVideoOrientation)avOrientationForDeviceOrientation:(UIDeviceOrientation)deviceOrientation
{
    AVCaptureVideoOrientation result = AVCaptureVideoOrientationLandscapeRight;
    switch (deviceOrientation) {
        case UIDeviceOrientationLandscapeRight:
            result = AVCaptureVideoOrientationLandscapeLeft;
            break;
        case UIDeviceOrientationLandscapeLeft:
            result = AVCaptureVideoOrientationLandscapeRight;
            break;
        case UIDeviceOrientationPortrait:
            result = AVCaptureVideoOrientationPortrait;
            break;
        case UIDeviceOrientationPortraitUpsideDown:
            result = AVCaptureVideoOrientationPortraitUpsideDown;
            break;
        default:
            break;
    }
    return result;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return YES;
}
#endif
@end
